package fleditor.core.loader
{
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.system.LoaderContext;

	/**
	 *加载工厂类 
	 */	
	public class LoaderFactory
	{
		private var _loaderQueue:LoaderQueue;
		private var _loaderIds:int=1;
		
		/**
		 *加载工厂 
		 * 
		 */		
		public function LoaderFactory()
		{
		}
		
		private static var _instance:LoaderFactory;
		public static function get Instance():LoaderFactory
		{
			if(_instance == null)
			{
				_instance = new LoaderFactory();
			}
			return _instance;
		}
		
		/**
		 *加载工厂类注册 
		 */
		public function register():void
		{
			_loaderQueue=new LoaderQueue();
		}
		
		/**
		 * 创建加载 
		 * @param loaderType 加载类型
		 * @param url 加载对象路径
		 * @param autoExecute 是否自动执行加载
		 * @param callBack 加载完成后返回方法
		 * @param repeat 如果加载失败，重复加载次数
		 * @param loaderContext LoaderContext
		 * @param urlVariables 如果为url方式时，其加载时的参数
		 * @param requestMethod 如果为url方式时Method的方式
		 * @return BaseLoader
		 * 
		 */		
		public function createLoader(loaderType:String, url:String, autoExecute:Boolean=true, callBack:Function=null, repeat:int=3, loaderContext:LoaderContext=null, urlVariables:URLVariables=null, requestMethod:String=URLRequestMethod.GET):BaseLoader
		{
			var baseLoader:BaseLoader;
			switch(loaderType)
			{
				case LoaderType.Loader:
					baseLoader=new LoaderBase(getLoaderID, url, autoExecute, callBack, repeat, loaderContext);
					break;
				case LoaderType.URLLoader:
					baseLoader=new URLLoaderBase(getLoaderID, url, autoExecute, callBack, repeat, urlVariables, requestMethod);
					break;
			}
			
			_loaderQueue.addLoader(baseLoader);
			
			return baseLoader;
		}
		
		/**
		 * 执行加载
		 */
		public function execute(baseLoader:BaseLoader):void
		{
			if(baseLoader.isLoading || baseLoader.isComplete || baseLoader.isSuccess) return;
			baseLoader.execute();
		}
		
		/**
		 * 设置当前加载的ID 
		 * @return int
		 * 
		 */		
		private function get getLoaderID():int
		{
			return _loaderIds+=1;
		}
		
		/**
		 *执行加载列表中全部加载项 
		 * 
		 */		
		public function executeAll():void
		{
			_loaderQueue.execute();
		}
	}
}